package pshop.servlet.util;

import pshop.Bestellung;
import pshop.Warenkorb;
import pshop.db.OfyService;
import pshop.servlet.ServletConstants;
import pshop.servlet.util.EmailUtils;
import pshop.servlet.util.Log;
import pshop.servlet.util.PersonUtils;
import pshop.servlet.util.SessionUtils;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public abstract class BestellUtils
{
   public static void order(HttpServletRequest req)
   {
      Warenkorb wk = SessionUtils.getSessionWarenkorb(req);
      Bestellung best = SessionUtils.getSessionBestellung(req);
      best.setWarenkorb(wk);
      req.getSession().setAttribute(ServletConstants.ATTR_BEST, best);
   }

   public static String confirm(HttpServletRequest req)
   {
      Bestellung best = SessionUtils.getSessionBestellung(req);
      try
      {
         best.setKunde(PersonUtils.getPerson(req));
         best.setAdresse(PersonUtils.getAdresse(req));
         best.setKommentar(req.getParameter("kommentar"));
         best.setZahlart(req.getParameter("zahlungsart"));
         best.setVersand(req.getParameter("versand"));
         req.getSession().setAttribute(ServletConstants.ATTR_BEST, best);
      }
      catch (Exception e)
      {
         Log.logError(e);
         req.getSession().setAttribute(ServletConstants.ATTR_FORM_ERROR, e.getLocalizedMessage());
         return "bestellen.jsp";
      }
      return "bestaetigen.jsp";
   }

   public static void sendOrder(HttpServletRequest req)
   {
      Bestellung best = SessionUtils.getSessionBestellung(req);
      best.setBestellDatum(new Date());
      // Bestellung speichern

      OfyService.ofy().save().entity(best).now();

      EmailUtils.sendBestMail(best, req);
      req.getSession().removeAttribute(ServletConstants.ATTR_BEST);
      req.getSession().removeAttribute(ServletConstants.ATTR_WK);
      req.getSession().setAttribute(ServletConstants.ATTR_BEST_ID, best.getId());
   }
}